<?php
/**
 * Created by PhpStorm.
 * User: coolinmind
 * Date: 25/01/2019
 * Time: 17:00
 */

namespace App\Services\UCenter\UCenter;


use App\Models\Fund\IntegralAccount;
use App\Models\Fund\IntegralOptionLog;
use App\Models\Order\Orders;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Request;

class OrderLogic
{
    /**
     * 生成订单
     * @param $data
     * @return array
     */
    public function createOrder($data)
    {

        $newData = [
            'user_id' => $data['user_id'],
            'goods_id' => $data['id'],
            'number' => $this->createOrderNum(),
            'price' => 0.01,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ];
        DB::beginTransaction();
        try {
            $res = $this->deductIntegral($data['user_id'], $newData['price']);
            if ($res['status'] !== SUCCESS_STATUS) {
                DB::rollBack();
                new \Exception('扣除积分失败');
            }
            Orders::insert($newData);
            DB::commit();
            return auto_success(null,'兑换成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return auto_failure($e->getMessage(), '生成订单失败');
        }
    }

    /**
     * 扣除积分并且写入积分操作日志
     * @param $userId
     * @param $num
     * @param string $remark
     * @return array
     */
    private function deductIntegral($userId, $num, $remark = '')
    {
        $account = IntegralAccount::where(['user_id' => $userId])->first();
        $bccompRes = bccomp($account->available_integral, $num);
        if (!$bccompRes)
            new \Exception('积分不足');
        $newAvailable = bcsub($account->available_integral, $num,2);
        $newTotal = bcsub($account->total, $num,2);
        $newExpend = bcadd($account->expend, $num,2);
        $account->available_integral = $newAvailable;
        $account->total = $newTotal;
        $account->expend = $newExpend;

        $logData = [
            'user_id' => $userId,
            'type' => 'transfer',
            'integral' => $num,
            'total' => $newTotal,
            'income' => $account->income,
            'expend' => $newExpend,
            'available_integral' => $newAvailable,
            'freeze' => $account->freeze,
            'remark' => $remark,
            'user_info' => '{}',
            'opposite_info' => '{}',
            'create_ip' => Request::getClientIp(),
            'update_ip' => Request::getClientIp(),
            'create_time' => NOW,
            'update_time' => NOW
        ];

        try {
            IntegralOptionLog::insert($logData);
            $res = $account->save();
            return auto_success($res);
        } catch (\Exception $e) {
            return auto_failure($e->getMessage(), '扣除积分失败');
        }
    }

    private function createOrderNum()
    {
        $num = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        return $num;
    }

    /**
     * 获取订单列表
     * @param $data
     * @return array
     */
    public function getOrderList($data)
    {
        $list = Orders::where(['user_id' => $data['user_id']])->paginate($data['per_page']);
        return auto_return($list);
    }
}
